package com.kinyx.framework.security;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import com.kinyx.framework.Configs;
import com.kinyx.framework.annotation.assist.CanNotNull;
import com.kinyx.framework.annotation.assist.CanNull;
import com.kinyx.framework.annotation.assist.ReturnNotNull;
import com.kinyx.framework.annotation.assist.Tester;
import com.kinyx.framework.annotation.assist.Throws;
import com.kinyx.framework.exception.KRuntimeException;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * BASE64编码/解码工具类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Tester("com.kinyx.framework.security.KBASE64_Tester_")
public final class KBASE64 {

	/**
	 * 编码
	 * @param bytes 字节数组
	 * @param charset 字符集
	 * @return BASE64字符串
	 */
	@ReturnNotNull
	@Throws(at = "KBase64.encode(byte[], String)", value = "UnsupportedEncodingException", when = "new String(byte[], String)")
	public static String encode(@CanNotNull final byte[] bytes, @CanNull(defaultValue = "Configs.default_KBase64_charset") final String charset) {
		if (charset == null) { return encode(bytes, Configs.default_KBase64_charset); }
		try {
			return new String(Base64.getEncoder().encode(bytes), charset);
		} catch (final UnsupportedEncodingException e) {
			throw new KRuntimeException(e);
		}
	}

	/**
	 * 编码
	 * @param bytes 字节数组
	 * @return BASE64字符串
	 */
	public static String encodeToString(@CanNotNull final byte[] bytes) {
		return Base64.getEncoder().encodeToString(bytes);
	}

	/**
	 * 解码
	 * @param base64 BASE64字符串
	 * @return 字节数组
	 */
	@ReturnNotNull
	public static byte[] decode(@CanNotNull final String base64) {
		return Base64.getDecoder().decode(base64);
	}

}
